package com.saas.tenant.controller;

import com.saas.tenant.dto.LoginDTO;
import com.saas.tenant.dto.TenantDTO;
import com.saas.tenant.resp.LoginResp;
import com.saas.tenant.service.TenantService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@RequestMapping("/api/tenant")
@RequiredArgsConstructor
public class TenantController {

    private final TenantService tenantService;

    @PostMapping("/register")
    public Map<String, Object> register(@Valid @RequestBody TenantDTO dto) {
        return tenantService.createTenantWithAdmin(dto);
    }

    @PostMapping("/login")
    public LoginResp login(@Valid @RequestBody LoginDTO dto) {
        return tenantService.login(dto);
    }

    @GetMapping("/me")
    public Map<String, Object> me(HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");

        // 1. 生成与登录时相同的密钥
        SecretKey key = Keys.hmacShaKeyFor("12345678901234567890123456789012"
                .getBytes(StandardCharsets.UTF_8));

        // 2. 解析并验签
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();

        return Map.of("userId", claims.getSubject(),
                "tenantId", claims.get("tenantId"));
    }
}